import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from '../entity/role.entity';
import { Context } from '@midwayjs/koa';
import { CreateRoleDto, UpdateRoleDto } from '../dto/Role.dto';

@Provide()
export class RoleService {
  @InjectEntityModel(Role)
  RoleModel: Repository<Role>;

  @Inject()
  ctx: Context;

  /**
   * 创建新角色
   * @param createRoleDto 
   */
  async createRole(createRoleDto: CreateRoleDto) {
    const { name, description } = createRoleDto;
    console.log(name)
    // 检查是否存在同名角色
    const existingRole = await this.RoleModel.findOne({ where: { name } });
    if (existingRole) {
      return { success: false, message: '角色名称已存在' };
    }

    // 创建并保存角色
    const role = this.RoleModel.create({ name, description });
    const savedRole = await this.RoleModel.save(role);

    return { success: true, data: savedRole, message: '角色创建成功' };
  }

  /**
   * 获取所有角色
   */
  async getAllRoles() {
    const roles = await this.RoleModel.find();
    return { success: true, data: roles, message: '获取角色列表成功' };
  }

  /**
   * 根据 ID 获取角色
   * @param id UUID 
   */
  async getRoleById(id: string) {
    const role = await this.RoleModel.findOne({ where: { id } });
    if (!role) {
      return { success: false, message: '角色未找到' };
    }
    return { success: true, data: role, message: '获取角色详情成功' };
  }

  /**
   * 更新角色信息
   * @param id UUID 
   * @param updateRoleDto 
   */
  async updateRole(id: string, updateRoleDto: UpdateRoleDto) {
    const role = await this.RoleModel.findOne({ where: { id } });
    if (!role) {
      return { success: false, message: '角色未找到' };
    }

    // 更新角色字段
    Object.assign(role, updateRoleDto);
    const updatedRole = await this.RoleModel.save(role);

    return { success: true, data: updatedRole, message: '角色更新成功' };
  }

  /**
   * 删除角色
   * @param id UUID 
   */
  async deleteRole(id: string) {
    const role = await this.RoleModel.findOne({ where: { id } });
    if (!role) {
      return { success: false, message: '角色未找到' };
    }

    // 删除角色
    await this.RoleModel.remove(role);
    return { success: true, message: '角色删除成功' };
  }

  /**
   * 检查角色是否存在
   * @param id UUID 
   */
  async roleExists(id: string): Promise<boolean> {
    const role = await this.RoleModel.findOne({ where: { id } });
    return !!role;
  }

  /**
   * 分页获取角色列表
   * @param pageIndex 当前页码
   * @param pageSize 每页记录数
   */
  async getRolesByPage(pageIndex: number, pageSize: number) {
    const [roles, total] = await this.RoleModel.findAndCount({
      skip: (pageIndex - 1) * pageSize,
      take: pageSize,
      order: { createDate: 'DESC' },
    });

    return {
      success: true,
      data: roles,
      total,
      message: '分页获取角色列表成功',
    };
  }
}
